package com.myblog.myblog.utils;

import java.lang.reflect.Method;

import com.myblog.myblog.myException.MyException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;

/**
 * 定时任务的实现
 * @author gyl
 * @data 2020/5/5 13:35
 */
public class ScheduleRunnable implements  Runnable {

    private Object target;
    private Method method;
    private String params;

    public ScheduleRunnable(String beanName, String methodName, String params) throws NoSuchMethodException {
        this.target = SpringContextUtils.getBean(beanName);
        this.params = params;

        if(StringUtils.isNotBlank(params)){
            this.method = target.getClass().getDeclaredMethod(methodName, String.class);
        } else {
            this.method = target.getClass().getDeclaredMethod(methodName);
        }
    }

    @Override
    public void run() {

        try {

            ReflectionUtils.makeAccessible(method);
            if(StringUtils.isNotBlank(params)){
                method.invoke(target, params);
            } else {
                method.invoke(target);
            }

        } catch (java.lang.Exception e){
            throw new MyException("执行定时任务失败",e);
        }

    }
}